package com.xdh.zzqh.utils

import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import android.view.View
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch


private val uiScope = CoroutineScope(Dispatchers.Main + Job())

fun View.onClick(cb: suspend () -> Unit) {
    this.setOnClickListener { uiScope.launch { cb() } }
}

fun runOnUi(cb: suspend () -> Unit) {
    uiScope.launch { cb() }
}

fun runOnUiWithInit(cb: suspend () -> Unit) {
    uiScope.launch {
        waitInit()
        cb()
    }
}

private class TaskThread(name: String) : HandlerThread(name) {
    init {
        start()
    }
}

object DbTask : Handler(TaskThread("db").looper)

object AppTask : Handler(Looper.getMainLooper())

private class PromiseTask<R>(val cb: () -> R) : Runnable {

    private val future = CompletableDeferred<R>()

    suspend fun await(): R {
        DbTask.post(this)
        return future.await()
    }

    override fun run() {
        try {
            val ret = cb()
            future.complete(ret)
        } catch (e: Exception) {
            future.completeExceptionally(e)
        }
    }
}

suspend fun<R> runWithDb(cb: () -> R): R {
    return PromiseTask(cb).await()
}













